package rank;

import java.util.HashSet;
import java.util.Set;

import system.Config;
import system.L;

public class RandomCache {
	public GradeRandomSet[] grades = new GradeRandomSet[Config.gradeScore.length];

	public RandomCache() {
		for (int i = 0; i < Config.gradeScore.length; i++) {
			grades[i] = new GradeRandomSet();
		}
	}

	public synchronized void add(int level, String guid, long time) {
		GradeRandomNode node = null;
		for (GradeRandomSet grade : grades) {
			node = grade.remove(guid);
			if (node != null)
				break;
		}
		if (node == null) {
			node = new GradeRandomNode();
			node.guid = guid;
		}
		grades[level].addNode(node, time);
	}

	public synchronized Set<String> pick(int level, String guid) {
		int count = Config.PVP_RANDOM_COUNT_PER_LEVEL * 3;
		Set<String> result = new HashSet<String>();
		grades[level].selectRandom(guid, result, count);
		if (result.size() < count) {
			int cl = level - 1;
			while (cl >= 0 && result.size() < count) {
				grades[cl].selectRandom(guid, result, count - result.size());
				cl--;
			}
		}
		return result;
	}

	public synchronized void print() {
		int i = 0;
		for (GradeRandomSet grade : grades) {
			L.info("Grade:" + (i++) + "  Count:"
					+ grade.nodeIndex.size() + "  Count2:" + grade.nodesOrderByTime.size());
//			grade.print();
		}
	}
	
	public synchronized void removePlayer(String guid) {
		GradeRandomNode node = null;
		for (GradeRandomSet grade : grades) {
			node = grade.remove(guid);
			if (node != null) {
				L.info("remove player from random cache:"+guid);
				break;
			}
		}		
	}

}
